#include "StatusIndicator.h"
#include <QPainter>
#include <QFont>
#include <QMouseEvent>
#include <QToolTip>
#include <QApplication>
#include <QFontMetrics>
#include <QLinearGradient>
#include <QRadialGradient>
#include <QGraphicsBlurEffect>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>

StatusIndicator::StatusIndicator(const QString &deviceName, QWidget *parent)
    : QLabel(parent),
    m_deviceName(deviceName),
    m_currentStatus(NotSelected),
    m_dataQuality(0.0),
    m_blinkState(false),
    m_hovered(false),
    m_blinkTimer(new QTimer(this))
{
    // 修改为水平布局，宽度更宽，高度更小
    setFixedSize(INDICATOR_WIDTH, INDICATOR_HEIGHT);
    setAlignment(Qt::AlignCenter);
    setCursor(Qt::PointingHandCursor);
    setObjectName("statusIndicator_" + deviceName);

    // 初始化默认字体
    m_labelFont = font();
    m_labelFont.setPointSize(10);
    m_labelFont.setBold(true);

    // 设置工具提示
    updateToolTip();

    // 设置闪烁定时器
    m_blinkTimer->setInterval(500); // 500ms闪烁间隔
    connect(m_blinkTimer, &QTimer::timeout, this, &StatusIndicator::updateBlink);

    // 移除背景框样式
    setStyleSheet("");

    // 启用鼠标跟踪以检测悬停
    setMouseTracking(true);

    // 支持半透明
    setAttribute(Qt::WA_TranslucentBackground);
}

// 添加设置标签字体的方法实现
void StatusIndicator::setLabelFont(const QFont &font)
{
    m_labelFont = font;
    update(); // 触发重绘以应用新字体
}

void StatusIndicator::setStatus(DeviceStatus status)
{
    if (m_currentStatus != status) {
        m_currentStatus = status;
        updateToolTip();
        setupBlink();
        update(); // 触发重绘
    }
}

void StatusIndicator::setDataQuality(double quality)
{
    m_dataQuality = qBound(0.0, quality, 1.0);
    updateToolTip();
    update();
}

void StatusIndicator::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制玻璃罩效果 - 只在悬停时显示
    if (m_hovered) {
        QLinearGradient bgGradient(0, 0, 0, height());
        bgGradient.setColorAt(0, QColor(240, 240, 240, 60));
        bgGradient.setColorAt(1, QColor(220, 220, 220, 40));

        painter.setPen(QPen(QColor(200, 200, 200, 80), 1));
        painter.setBrush(bgGradient);
        painter.drawRoundedRect(rect().adjusted(0, 0, -1, -1), 8, 8);
    }

    // 绘制状态指示灯 - 使用发光效果，与文本高度一致
    int indicatorSize = height() - 10; // 指示灯尺寸与文本高度一致
    QRect indicatorRect(width() - indicatorSize - 10, 5, indicatorSize, indicatorSize);
    QColor statusColor = getStatusColor();

    // 创建离屏渲染用于实现磨砂玻璃效果
    QPixmap tempPixmap(indicatorSize * 2, indicatorSize * 2);
    tempPixmap.fill(Qt::transparent);
    QPainter tempPainter(&tempPixmap);
    tempPainter.setRenderHint(QPainter::Antialiasing);

    // 绘制基础灯光效果
    QRadialGradient glowGradient(tempPixmap.width()/2, tempPixmap.height()/2, indicatorSize);
    glowGradient.setColorAt(0, statusColor.lighter(130));
    glowGradient.setColorAt(0.5, statusColor);
    glowGradient.setColorAt(1, statusColor.darker(110));

    // 如果是连接状态且在闪烁，调整颜色
    if (m_currentStatus == Selected && m_blinkState) {
        statusColor = statusColor.lighter(150);
        glowGradient.setColorAt(0, statusColor.lighter(130));
        glowGradient.setColorAt(0.5, statusColor);
        glowGradient.setColorAt(1, statusColor.darker(110));
    }

    // 绘制基础圆形
    tempPainter.setPen(Qt::NoPen);
    tempPainter.setBrush(glowGradient);
    tempPainter.drawEllipse(QRect(indicatorSize/2, indicatorSize/2, indicatorSize, indicatorSize));

    // 添加磨砂玻璃效果 - 使用图形视图框架应用模糊
    QGraphicsScene scene;
    QGraphicsPixmapItem item(tempPixmap);

    // 应用模糊效果
    QGraphicsBlurEffect *blurEffect = new QGraphicsBlurEffect();
    blurEffect->setBlurRadius(1.5); // 轻微的模糊效果，模拟磨砂玻璃
    item.setGraphicsEffect(blurEffect);

    scene.addItem(&item);

    // 渲染模糊后的图像
    QPixmap blurredPixmap(tempPixmap.size());
    blurredPixmap.fill(Qt::transparent);
    QPainter blurPainter(&blurredPixmap);
    scene.render(&blurPainter);

    // 绘制模糊后的指示灯到主画布
    painter.drawPixmap(indicatorRect.x() - indicatorSize/2, indicatorRect.y() - indicatorSize/2, blurredPixmap);

    // 添加玻璃反光效果
    painter.setPen(Qt::NoPen);
    QLinearGradient reflectionGradient(
        indicatorRect.x(), indicatorRect.y(),
        indicatorRect.x() + indicatorRect.width()/2, indicatorRect.y() + indicatorRect.height()/2
        );
    reflectionGradient.setColorAt(0, QColor(255, 255, 255, 90));
    reflectionGradient.setColorAt(1, QColor(255, 255, 255, 0));

    painter.setBrush(reflectionGradient);
    painter.drawEllipse(
        indicatorRect.x() + indicatorRect.width()/4,
        indicatorRect.y() + indicatorRect.height()/4,
        indicatorRect.width()/3,
        indicatorRect.height()/3
        );

    // 绘制设备名称 - 在指示灯左侧，与按钮右端对齐
    // 使用设置的字体而不是硬编码的字体
    painter.setFont(m_labelFont);

    // 绘制文字
    painter.setPen(QColor(40, 40, 40));
    QRect textRect = QRect(TEXT_LEFT_MARGIN, 0, width() - indicatorSize - 25, height());
    painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, m_deviceName);

    if (m_currentStatus == Working && m_dataQuality > 0) {
        QString qualityText = QString("%1%").arg(static_cast<int>(m_dataQuality * 100));

        QColor qualityColor;
        if (m_dataQuality >= 0.8) {
            qualityColor = QColor(76, 175, 80); // 绿色
        } else if (m_dataQuality >= 0.6) {
            qualityColor = QColor(255, 193, 7); // 黄色
        } else {
            qualityColor = QColor(244, 67, 54); // 红色
        }

        painter.setPen(qualityColor);
        painter.setFont(QFont("Arial", 8, QFont::Bold));
    }
}

void StatusIndicator::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 发出点击信号
        emit clicked();
    }
    QLabel::mousePressEvent(event);
}

void StatusIndicator::enterEvent(QEnterEvent *event)
{
    m_hovered = true;
    update();
    QLabel::enterEvent(event);
}

void StatusIndicator::leaveEvent(QEvent *event)
{
    m_hovered = false;
    update();
    QLabel::leaveEvent(event);
}

void StatusIndicator::updateBlink()
{
    m_blinkState = !m_blinkState;
    update();
}

QColor StatusIndicator::getStatusColor() const
{
    switch (m_currentStatus) {
    case NotSelected:
        return QColor(158, 158, 158); // 灰色
    case Selected:
        return QColor(244, 67, 54);   // 红色
    case Connected:
        return QColor(76, 175, 80);   // 绿色
    case Working:
        return QColor(33, 150, 243);  // 蓝色
    default:
        return QColor(158, 158, 158);
    }
}

void StatusIndicator::setupBlink()
{
    if (m_currentStatus == Selected) {
        m_blinkTimer->start();
    } else {
        m_blinkTimer->stop();
        m_blinkState = false;
    }
}

void StatusIndicator::updateToolTip()
{
    QString tooltip = QString("<b>%1 设备</b><br>").arg(m_deviceName);

    switch (m_currentStatus) {
    case NotSelected:
        tooltip += "<span style='color:#9E9E9E'>状态: 未选择</span><br>"
                   "点击此处可查看详细信息";
        break;
    case Selected:
        tooltip += "<span style='color:#F44336'>状态: 已选择但未连接</span><br>"
                   "请点击连接设备按钮进行连接";
        break;
    case Connected:
        tooltip += "<span style='color:#4CAF50'>状态: 已连接</span><br>"
                   "设备已就绪，可以开始数据采集";
        break;
    case Working:
        tooltip += QString("<span style='color:#2196F3'>状态: 正常工作中</span><br>"
                           "数据质量: <b>%1%</b>").arg(int(m_dataQuality * 100));
        break;
    }

    setToolTip(tooltip);
}
